import { getCccTableConfFedUrl } from '@/api/api-instances/business.js'
import store from '@/store/index'
import * as Types from '@/store/mutation-types'

// todo 如果要开启配表缓存，请填写这个项目的 ActivityName，避免配表本地缓存冲突
const ActivityName = ''
export const getTableConfig = (useLocalCache = false) => {
  // eslint-disable-next-line
  return new Promise(async (resolve, reject) => {
    try {
      // 优先取localStorage配表数据，不阻塞流程
      let localData = null
      if (useLocalCache) {
        localData = getLocalConfig()
        if (localData) {
          updateTableConfig(localData)
          resolve(localData)
        }
      }

      await reGetNewConfig(localData).catch(() => {})
      resolve('continue')
    } catch (err) {
      console.error('获取配表失败:', err)
      reject(err)
    }
  })
}

// 获取配表
async function reGetNewConfig(localData, maxRetries = 3, retryDelay = 1000, currentRetry = 0) {
  try {
    const res = await getCccTableConfFedUrl()
    const fedUrl = res.fed_url

    if (!fedUrl) {
      return
    }

    // 如果版本号有更新，则刷新数据
    if (res?.version && localData?.version !== res?.version) {
      const tableData = (await getJson(fedUrl).catch((err) => {})) || {}
      if (!tableData) {
        return
      }

      try {
        updateTableConfig(tableData)
        // 更新最新配表到本地localStorage
        updateLocalConfig(tableData)
      } catch (e) {}
    }
  } catch (error) {
    // 判断是否还可以重试
    if (currentRetry < maxRetries) {
      // 等待重试延迟
      // eslint-disable-next-line
      await new Promise((resolve) => setTimeout(resolve, retryDelay))

      // 重试
      return reGetNewConfig(localData, maxRetries, retryDelay, currentRetry + 1)
    } else {
      return null
    }
  }
}

function updateTableConfig(tableData) {
  store.commit(Types.SET_TABLE_CONF, tableData)
}

function getLocalConfig() {
  let ret = null
  const str = uni.getStorageSync(`${ActivityName}_table`)
  try {
    if (str) {
      ret = JSON.parse(str)
    }
  } catch (e) {}
  return ret
}

function updateLocalConfig(tableConfig) {
  try {
    const str = JSON.stringify(tableConfig)
    uni.setStorageSync(`${ActivityName}_table`, str)
  } catch (e) {}
}

function getJson(url) {
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      complete: (res) => {
        resolve(res.data)
      },
      fail: (error) => {
        error.errorUrl = url
        reject(error)
      },
      timeout: 10000,
    })
  })
}
